package com.cardone.platform.authority.service;

import com.cardone.context.*;
import com.cardone.platform.authority.dao.*;
import com.cardone.platform.authority.dto.*;
import com.google.common.collect.*;
import lombok.*;
import org.apache.commons.beanutils.*;
import org.springframework.transaction.annotation.*;
import org.springframework.util.*;

import java.lang.reflect.*;
import java.util.*;

/**
 * 角色服务
 *
 * @author yaohaitao
 */
@Getter
@Setter
@Transactional(readOnly = true)
@lombok.extern.slf4j.Slf4j
public class RoleDefaultService extends com.cardone.common.service.SimpleDefaultService<com.cardone.platform.authority.dto.RoleDto> implements RoleService {
    @Override
    public RoleDao getDao() {
        return ContextHolder.getBean(RoleDao.class);
    }

    @Override
    @Transactional
    public int deleteByIds(final String ids) {
        int deleteCount = ContextHolder.getBean(RoleDao.class).deleteByIds(ids);

        deleteCount += ContextHolder.getBean(RolePermissionDao.class).deleteByRoleIds(ids);

        deleteCount += ContextHolder.getBean(RoleUserDao.class).deleteByRoleIds(ids);

        deleteCount += ContextHolder.getBean(UsGroupRoleDao.class).deleteByRoleIds(ids);

        return deleteCount;
    }

    @Override
    @Transactional
    public <P> P saveForPermissionIds(final Class<P> mappedClass, final RoleDto saveRole) {
        final P p = this.saveByIdOrCode(mappedClass, saveRole);

        String roleId = null;

        try {
            roleId = BeanUtils.getProperty(p, Attributes.id.name());
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            RoleDefaultService.log.error(e.getMessage(), e);
        }

        ContextHolder.getBean(RolePermissionDao.class).saveRoleIdAndPermissionIds(roleId, saveRole.getPermissionIds());

        return p;
    }

    @Override
    @Transactional(readOnly = true)
    public <P> List<P> findListByUserId(final Class<P> mappedClass, final String userId) {
        return ContextHolder.getBean(RoleDao.class).findListByUserId(mappedClass, userId);
    }

    @Override
    @Transactional(readOnly = true)
    public String readIdByCode(final RoleDto readRole) {
        return ContextHolder.getBean(RoleDao.class).readIdByCode(readRole);
    }

    @Override
    @Transactional(readOnly = true)
    public List<String> readIdListByUserId(final String userId) {
        final List<RoleDto> roleList = ContextHolder.getBean(RoleService.class).findListByUserId(RoleDto.class, userId);

        final List<String> idList = Lists.newArrayList();

        if (CollectionUtils.isEmpty(roleList)) {
            return idList;
        }

        for (final RoleDto role : roleList) {
            idList.add(role.getId());
        }

        return idList;
    }
}